package com.wz.common.controller;


import com.wz.common.bean.ResultBean;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>Project: wz_api - BaseController
 * <p>Powered by pisces On 2022-01-13 21:02:31
 * <P>Created by IntelliJ IDEA
 *
 * @author ww606851@163.com
 * @version 1.0
 * @description:
 * @since 8
 */

public abstract class BaseController {
    private final int SUCCESS=200;
    private final int FAIL = 0;

   protected ResultBean success(String msg){
        return new ResultBean(SUCCESS,msg,null);
    }

    protected ResultBean success(String msg,Object data){
        return new ResultBean(SUCCESS,msg,data);
    }
    protected ResultBean success(Object data){
        return new ResultBean(SUCCESS,Message.COMMON,data);
    }

    protected ResultBean fail(String msg){
        return new ResultBean(FAIL,msg,null);
    }
    protected ResultBean fail(String msg,Object data){
        return new ResultBean(FAIL,msg,data);
    }
    protected ResultBean validateFail(Object data){
        return new ResultBean(FAIL,Message.VALIDATION_ERROR,data);
    }

    protected interface Message{
       String COMMON = "内容";
       String VALIDATION_ERROR ="验证错误";
       String SAVE_SUCCESS = "保存成功~";
       String SAVE_FAIL = "保存失败！";
    }

    protected  Map validate(BindingResult result){
        List<FieldError> errorList = result.getFieldErrors();
        Iterator<FieldError> it = errorList.iterator();
        Map map = new HashMap();
        while (it.hasNext()) {
            FieldError fieldError = it.next();
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return map;
    }
}
